package com.woniuxy.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.result.Result;
import com.woniuxy.util.JWTUtil;
import com.woniuxy.util.TokenEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //设置响应的格式为json，编码为utf-8
        response.setContentType("application/json;charset=utf-8");
        //获取请求的url
        String url = request.getRequestURI();
        System.out.println(url);
        //获取请求的token
        String token = request.getHeader("token");
        System.out.println("token序列：\n"+token);
        //创建响应数据
        Result result = new Result();
        //创建ObjectMapper对象进行返回的结果的序列化
        ObjectMapper objectMapper = new ObjectMapper();
        if(token!=null&&!token.trim().isEmpty()){
            //token有值，表示登录
            //token的状态分为三个状态:有效，合法但过期，不合法的序列
            TokenEnum tokenEnum = JWTUtil.verify(token);
            //判断token的状态是否合法
            if(TokenEnum.TOKENSUCCESS == tokenEnum){
                //需要在用户每一次请求的时候刷新token的过期时间
                //获取用户的信息
                Long uid = JWTUtil.getUid(token);
                String uname = JWTUtil.getUsername(token);
                //重新生成token
                String token1 = JWTUtil.generateToken(uid, uname);
                //发送给前端
                response.setHeader("token",token1);
                System.out.println("新的token:\n"+token1);
                //前后端分离的项目，必须暴露响应头，否则前端收不到响应头
                response.setHeader("Access-Control-Expose-Headers","token");
                //合法放行
                return true;
            }
            if(TokenEnum.TOKENEXPIRE == tokenEnum){
                //过期
                result.setMsg("token过期了");
                result.setCode(531);
                String josn = objectMapper.writeValueAsString(result);
                response.getWriter().write(josn);
                return false;//拦截
            }
            if(TokenEnum.TOKENINVALID == tokenEnum){
                result.setCode(532);
                result.setMsg("非法的token");
                String json = objectMapper.writeValueAsString(token);
                response.getWriter().write(json);
                return false;//拦截
            }
        }
        //没有登录
        result.setCode(530);
        result.setMsg("请求中未携带token!!");
        //把结果转换为json字符串
        String s = objectMapper.writeValueAsString(result);
        //用rsponse返回给前端
        response.getWriter().write(s);
//        response.sendRedirect("/login.html");//重定向
        return false;
    }
}
